<template>
  <div class="spl-container">
    <breadcrumb :data="pathData"></breadcrumb>
    <div class="emp-title">
      <p class="text-blue">设置用户账户信息</p>
    </div>
    <div style="padding: 20px;">
      <!-- 用户上传 -->
      <div class="clearfix">
        <div class="fl">
          <img v-if="imageUrl" :src="imageUrl" width="115px" height="115px" style="border-radius: 200px">
          <img v-else src="../../assets/images/default-headImg.png" width="115px" height="115px"
               style="border-radius: 200px">
        </div>
        <div class="fl pl-20">
          <p style="line-height: 115px;">用户名称：{{userInfo.userName}}</p>
        </div>
        <div class="fr pl-20">
          <p style="margin-top: 100px;"><i
            class="el-icon-date text-blue mr-5"></i>账号启用时间： {{this.$moment(userInfo.approveTime).format('YYYY-MM-DD HH:mm:ss')}}
          </p>
        </div>
      </div>
      <div class="editHeadImg">
        <el-divider content-position="left">
          <div>
            <el-upload
              class="fl text-center"
              ref="upload"
              action="/api/sys/no-limit/upload/single"
              :headers="this.$global.setHeaders"
              :before-upload="beforeAvatarUpload"
              :on-success="handleAvatarSuccess"
              :show-file-list="false"
                accept=".jpg,.jpeg,.png,.gif,.JPG,.JPEG,.PNG,.GIF"
              :auto-upload="true" :multiple="false">
              <span class="text-blue">修改头像</span>
            </el-upload>
          </div>
        </el-divider>
      </div>

      <!-- 用户角色： -->
      <el-row class="edit-type">
        <el-col :span="17">
          <div class="mt-15 clearfix">
            <div class="img">
              <img src="../../assets/Verification/me-1.png" alt="" width="48px" height="48px">
            </div>
            <span class="text" style="margin-top: 10px;">用户角色：
              <span v-show="!isEditUserRoles">{{userInfo.roles | parseRoles()}}</span>
              <el-select multiple v-show="isEditUserRoles" class="w-250" v-model="userRoles" collapse-tags>
                <el-option v-for="(item, index) in roles" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
              </el-select>
            </span>
          </div>
        </el-col>
        <el-col :span="7">
          <div class="grid-content bg-purple userrole text-right" v-show="!isEditUserRoles">
            <el-button type="primary" plain class="s-btn mt-12" @click="editRoleName">修改</el-button>
          </div>
          <div class="grid-content bg-purple userrole text-right" v-show="isEditUserRoles">
            <el-button class="s-btn mt-12" @click="isEditUserRoles=false">取消</el-button>
            <el-button type="primary" class="s-btn mt-12" @click="saveEditUserRoles">保存</el-button>
          </div>
        </el-col>
      </el-row>
      <el-divider></el-divider>
      <!-- 手机号码： -->
      <el-row class="edit-type">
        <el-col :span="17">
          <div class="clearfix">
            <div class="img">
              <img src="../../assets/Verification/iphone-1.png" alt="" width="30px" height="54px">
            </div>
            <span class="text" style="margin-top: 13px;">手机号码：{{userInfo.mobile}}</span>
          </div>
        </el-col>
        <el-col :span="7">
          <div class="grid-content bg-purple userrole text-right">
            <el-button type="primary" plain class="s-btn mt-5" @click="doChangePhone">修改</el-button>
          </div>
        </el-col>
      </el-row>
      <el-divider></el-divider>
      <!-- 用户邮箱：-->
      <el-row class="edit-type">
        <el-col :span="17">
          <div class="clearfix" style="padding-top: 7px;padding-bottom: 7px;">
            <div class="img">
              <img src="../../assets/Verification/emial-1.png" alt="" width="48px" height="36px">
            </div>
            <span class="text" style="margin-top: 5px;">用户邮箱：
              <span v-show="!isEditUserEmail">{{userInfo.email}}</span>
              <el-form :model="editUserEmail" ref="editUserEmail" class="inlineBlock">
                <el-form-item prop="email" :rules="[{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }]">
                  <el-input v-show="isEditUserEmail" class="w-250" v-model="editUserEmail.email"></el-input>
                </el-form-item>
              </el-form>
            </span>
          </div>
        </el-col>
        <el-col :span="7">
          <div class="grid-content bg-purple userrole text-right" v-show="!isEditUserEmail">
            <el-button type="primary" plain class="s-btn mt-5" @click="isEditUserEmail=true">修改</el-button>
          </div>
          <div class="grid-content bg-purple userrole text-right" v-show="isEditUserEmail">
            <el-button class="s-btn mt-12" @click="cancelEditUserEmail">取消</el-button>
            <el-button type="primary" class="s-btn mt-12" @click="saveEditUserEmail">保存</el-button>
          </div>
        </el-col>
      </el-row>
      <el-divider></el-divider>
      <!-- 用户密码 -->
      <el-row class="edit-type">
        <el-col :span="17">
          <div class="clearfix">
            <div class="img">
              <img src="../../assets/Verification/password-1.png" alt="" width="49px" height="57px">
            </div>
            <span class="text" style="line-height: 10px;margin-top: 15px;">用户密码</span><br>
            <span class="text" style="color: #B2B2B2;margin-top: -30px;line-height: 10px;">用于保护账号信息和登录安全</span>
          </div>
        </el-col>
        <el-col :span="7">
          <div class="grid-content bg-purple userrole text-right">
            <el-button type="primary" plain class="s-btn mt-5" @click="editUserPassword">修改</el-button>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 更换手机号 -->
    <el-dialog title="修改手机号码" class="spl-dialog" :visible.sync="editPhoneDialog" width="580px" center :before-close="cancelChangePhone">

      <el-form v-show="changePhoneStep==1" :model="oldPhoneForm" ref="oldPhoneForm" label-width="120px">
        <div class="add-ruleForm">
          <el-form-item label="当前手机号">
            <p v-text="oldPhoneForm.setPhone"></p>
          </el-form-item>
          <el-form-item label="图片验证码" prop="imgCode" :rules="{ required: true, message: '请输入图片验证码', trigger: 'blur' }">
            <el-input v-model="oldPhoneForm.imgCode" placeholder="请输入图片验证码" class="w-150 mr-15"></el-input>
            <img :src="oldPhoneForm.imgCodeUrl" class="imgCode">
            <span class="ml-10 inlineBlock lh-com">看不清？<span class="text-blue f-cursor"
                                                             @click="changeImgCode">换一张</span></span>
          </el-form-item>
          <el-form-item label="短信验证码" prop="verifyCode"
                        :rules="{ required: true, message: '请输入短信验证码', trigger: 'blur' }">
            <el-input v-model="oldPhoneForm.verifyCode" placeholder="请输入短信验证码" class="w-150"></el-input>
            <el-button type="primary" class="s-btn ml-15 w-120" @click="sendPhoneCode"
                       :disabled="oldPhoneForm.isSendOldPhone" v-text="oldPhoneForm.sendOldPhoneText"></el-button>
          </el-form-item>
        </div>
      </el-form>

      <el-form v-show="changePhoneStep==2" :model="newPhoneForm" ref="newPhoneForm" label-width="120px">
        <div class="add-ruleForm">
          <el-form-item label="新手机号" prop="phone" :rules="{ required: true, message: '请输入新手机号', trigger: 'blur' }">
            <el-input v-model="newPhoneForm.phone" placeholder="请输入新手机号" class="mr-15" style="width: 285px;"></el-input>
          </el-form-item>
          <el-form-item label="短信验证码" prop="verifyCode"
                        :rules="{ required: true, message: '请输入短信验证码', trigger: 'blur' }">
            <el-input v-model="newPhoneForm.verifyCode" placeholder="请输入短信验证码" class="w-150"></el-input>
            <el-button type="primary" class="s-btn ml-15 w-120" @click="sendPhoneCode"
                       :disabled="newPhoneForm.isSendNewPhone" v-text="newPhoneForm.sendNewPhoneText"></el-button>
          </el-form-item>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer operate-btns-bottom">
        <el-button @click="cancelChangePhone" class="mr-40">取 消</el-button>
        <el-button type="primary" :loading="changePhoneLoading" @click="changePhoneSave">确 认</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改用户密码" class="spl-dialog" :visible.sync="passwordDialog" width="500px" center :before-close="cancelEditPassword">
      <el-form :model="password" ref="password" label-width="120px">
        <div class="add-ruleForm">
          <el-form-item label="旧密码" prop="oldPassWord" :rules="[{ required: true, message: '请输入当前密码', trigger: 'blur'},{validator:this.validUserPassword,trigger:'blur'}]">
            <el-input v-model="password.oldPassWord" placeholder="请输入" class="w-250"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPassWord"
                        :rules="[{ required: true, message: '请输入新密码', trigger: 'blur' },{validator:this.checkPassword1,trigger:'blur'}]">
            <el-input v-model="password.newPassWord" type="password" placeholder="请输入" class="w-250" autocomplete="new-password"></el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="checkNew"
                        :rules="[{ required: true, message: '请再次输入新密码', trigger: 'blur' },{validator:this.checkPassword2,trigger:'blur'}]">
            <el-input v-model="password.checkNew" type="password" placeholder="请输入" class="w-250" autocomplete="new-password"></el-input>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer operate-btns-bottom">
        <el-button @click="cancelEditPassword" class="mr-40">取 消</el-button>
        <el-button type="primary" :loading="passwordBtnLoading" @click="savePassword">保 存</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
  import ElInput from "../../../node_modules/element-ui/packages/input/src/input";
  import ElFormItem from "../../../node_modules/element-ui/packages/form/src/form-item";
  export default {
    components: {
      ElFormItem,
      ElInput},
    data () {
      return {
        // 导航
        pathData: [
          {name: '企业管理'},
          {name: '用户管理'}
        ],
        imageUrl: '',
        isEditUserRoles: false,
        isEditUserEmail: false,
        changePhoneStep: 1,
        changePhoneLoading: false,
        editPhoneDialog: false,
        oldPhoneForm: {
          phone: '',
          setPhone: '',
          imgCode: '',
          verifyCode: '',
          stamp: '',
          imgCodeUrl: '',
          isSendOldPhone: false,
          sendOldPhoneText: '发送验证码'
        },
        newPhoneForm: {
          phone: '',
          verifyCode: '',
          isSendNewPhone: '',
          sendNewPhoneText: '发送验证码'
        },

        passwordDialog: false,
        passwordBtnLoading: false,
        password: {
          oldPassWord: '',
          newPassWord: '',
          checkNew: ''
        },
        userId: '',
        userInfo: {},
        userRoles: [],
        roles: [],
        editUserEmail:{
            email: ''
        },
        timer: null
      }
    },
    created() {
      this.userId = this.$route.query.userId
      this.getRoleOptions()
      this.$nextTick(() => {
        this.getUserInfo()
      })
    },
    filters: {
      parseRoles(value) {
        if (value && value.length > 0) {
          var roleNames = []
          value.forEach(item => {
            roleNames.push(item.roleName)
          })
          return roleNames.join(',')
        }
        return ''
      }
    },
    methods: {
      //获取用户可选角色的option项
      getRoleOptions() {
        this.$http({
          url: 'tenant/role/page',
          method: 'post',
          data: {
            filters: [{}],
            page: 1,
            query: [{}],
            sidx: '',
            size: 1000,
            sort: ''
          }
        }).then(({data}) => {
          this.roles = data.rows
        })
      },
      getImageUrl() {
        this.$http({
          url: '/sys/file/' + this.userInfo.imageHeader,
          method: 'get',
        }).then(({data}) => {
          this.imageUrl = data.data
        })
      },
      getUserInfo(){
        this.$http({
          url: '/tenant/user/page',
          method: 'post',
          data: {
            page: 1,
            size: 1,
            query: [
              {property: 'id', value: this.userId}
            ]
          }
        }).then(({data}) => {
          if(data.rows && data.rows.length>0){
            this.userInfo = data.rows[0]
            this.editUserEmail.email = this.userInfo.email
            this.oldPhoneForm.phone = this.userInfo.mobile
            if(this.userInfo.mobile){
              this.oldPhoneForm.setPhone = this.userInfo.mobile.replace(this.userInfo.mobile.substring(3,7), "****")
            }
            this.getImageUrl()
            this.getUserRoleIds()
          }
        })
      },
      getUserRoleIds(){
        this.userInfo.roles.forEach(item => {
            this.userRoles.push(item.id)
        })
      },
      handleAvatarSuccess (res, file) {
        this.imageUrl = URL.createObjectURL(file.raw)
        this.saveEdit({
          id: this.userId,
          properties: {imageHeader: res.data.id}
        })
      },
      saveEditUserRoles(){
        this.saveEdit({
          id: this.userId,
          properties: {roleIds: this.userRoles}
        },'保存成功')
        this.isEditUserRoles = false
        this.getUserInfo()
      },
      saveEditUserEmail(){
        this.$refs['editUserEmail'].validate((valid) => {
          if (valid) {
            this.saveEdit({
              id: this.userId,
              properties: {email: this.editUserEmail.email}
            },'保存成功')
            this.userInfo.email = this.editUserEmail.email
            this.isEditUserEmail = false
            this.getUserInfo()
          }
        })
      },
      cancelEditUserEmail(){
        this.editUserEmail.email = this.userInfo.email
        this.isEditUserEmail = false
      },
      saveEdit(editInfo,successMsg){
        this.$http({
          url: '/tenant/user/update',
          method: 'put',
          data: editInfo
        }).then(({data}) => {
          if (data.code === 0) {
            if(successMsg){
              this.$message.success(successMsg)
            }
          } else {
            this.$message.error(this.$global.errorMsg)
          }
        })
      },
      beforeAvatarUpload (file) {
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isLt2M
      },
      editRoleName () {
        this.isEditUserRoles = true
      },

      doChangePhone () {
        this.changeImgCode()
        this.editPhoneDialog = true
      },
      cancelChangePhone (done){
        this.changePhoneStep = 1
        this.oldPhoneForm.imgCode = ''
        this.oldPhoneForm.verifyCode = ''
        this.oldPhoneForm.isOldNewPhone = false
        this.oldPhoneForm.sendOldPhoneText = '发送验证码'

        this.newPhoneForm.phone = ''
        this.newPhoneForm.verifyCode = ''
        this.newPhoneForm.isSendNewPhone = false
        this.newPhoneForm.sendNewPhoneText = '发送验证码'
        if(this.timer){
          clearInterval(this.timer)
        }
        if(typeof done === 'function'){
          done()
        }else{
          this.editPhoneDialog = false
        }
      },
      // 更换验证码
      changeImgCode () {
        this.oldPhoneForm.stamp = String(new Date().getTime())
        this.oldPhoneForm.imgCodeUrl = '/api/sys/no-limit/picture/code/' + this.oldPhoneForm.stamp
      },

      //  发送短信验证码
      sendPhoneCode () {
        var stamp = this.oldPhoneForm.stamp
        this.$http({
          url: '/sys/no-limit/send/mobile/code',
          method: 'post',
          data: {
            businessType: 'v_c_login__',
            receiverAccount: this.changePhoneStep == 1?this.oldPhoneForm.phone:this.newPhoneForm.phone,
            selfValidate: true,
            stamp: stamp,
            validateCode: this.oldPhoneForm.imgCode
          }
        }).then(({data}) => {
          if (data.code == 0) {
            var s = 60;
            var that = this
            if(this.changePhoneStep==1){
              that.oldPhoneForm.isSendOldPhone = true
              that.oldPhoneForm.sendOldPhoneText = '重新获取(' + s + 's)'
              this.timer = setInterval(function () {
                if (s > 0) {
                  that.oldPhoneForm.sendOldPhoneText = '重新获取(' + s + 's)'
                } else {
                  that.oldPhoneForm.isSendOldPhone = false
                  that.oldPhoneForm.sendOldPhoneText = '重新获取'
                  clearInterval(that.timer)
                }
                --s
              }, 1000)
            }else{
              that.newPhoneForm.isSendNewPhone = true
              that.newPhoneForm.sendNewPhoneText = '重新获取(' + s + 's)'
              this.timer = setInterval(function () {
                if (s > 0) {
                  that.newPhoneForm.sendNewPhoneText = '重新获取(' + s + 's)'
                } else {
                  that.newPhoneForm.isSendNewPhone = false
                  that.newPhoneForm.sendNewPhoneText = '重新获取'
                  clearInterval(that.timer)
                }
                --s
              }, 1000)
            }

          } else {
            if (data.msg) {
              this.$message.error(data.msg)
            } else {
              this.$message.error(this.$global.errorMsg)
            }
          }
        })
      },
      changePhoneSave () {
        if (this.changePhoneStep == 1) {

          this.$refs.oldPhoneForm.validate((valid) => {
              if(valid){
                // 校验旧手机
                var that = this
                this.validPhoneCode(this.oldPhoneForm.phone,this.oldPhoneForm.verifyCode,function(){
                  if(that.timer){
                    clearInterval(that.timer)
                  }
                  that.changePhoneStep = 2
                  that.newPhoneForm.isSendNewPhone = false
                })

              }
          })
        } else {
          //  校验新手机
          this.$refs.newPhoneForm.validate((valid) => {
            var that = this
            if(valid){
              this.validPhoneCode(this.newPhoneForm.phone,this.newPhoneForm.verifyCode,function(){
                that.saveEdit({
                  id: that.userId,
                  properties: {mobile: that.newPhoneForm.phone}
                },'保存成功')
                that.cancelChangePhone()
                that.getUserInfo()
              })
            }
          })
        }
      },
      //
      validPhoneCode (phone,code,callBack) {
        this.$http({
          url: '/sys/no-limit/validate/mobile/code',
          method: 'post',
          data: {
            businessType: 'v_c_login__',
            receiverAccount: phone,
            stamp: this.oldPhoneForm.stamp,
            code: code,
            validateCode: this.oldPhoneForm.imgCode
          }
        }).then(({ data }) => {
          if (data.code == 0) {
            if(callBack){
                callBack()
            }
          } else {

            if(data.msg){
              this.$message.error(data.msg)
            }else{
              this.$message.error(this.$global.errorMsg)
            }
          }
        })
      },
      //验证用户旧密码
      validUserPassword (rule, value, callback){
        if (value != undefined && value != null && value != '') {
          this.$http({
            url: '/sys/no-limit/validate/password/old',
            method: 'post',
            data: {
              userId: this.userId,
              password: this.password.oldPassWord
            }
          }).then(({data}) => {
            if (data.code == -1) {
              if (!data.data) {
                callback(new Error(data.msg))
              } else {
                callback()
              }
            } else {
              callback()
            }
          })
        }
      },
      //修改用户登录密码
      editUserPassword (){
        this.passwordDialog = true
      },
      cancelEditPassword (done){
        this.password = {
          oldPassWord: '',
          newPassWord: '',
          checkNew: ''
        }
        this.passwordBtnLoading = false
        this.$refs.password.resetFields()
        if(typeof done === 'function'){
          done()
        }else{
          this.passwordDialog = false
        }
      },
      savePassword (){
        this.$refs.password.validate((valid) => {
          if (valid) {
            this.passwordBtnLoading = true
            this.saveEdit({
              id: this.userId,
              properties: {password: this.password.newPassWord}
            },'保存成功')
            //关闭修改密码窗口
            this.cancelEditPassword()
          }
        })
      },
      checkPassword1 (rule, value, callback) {
        if (this.password.checkNew != '') {
          this.$refs.password.validateField('checkNew')
        }
        callback()
      },
      checkPassword2 (rule, value, callback) {
        if (this.password.newPassWord != '' && this.password.checkNew != '' && this.password.newPassWord != this.password.checkNew) {
          callback(new Error('两次密码不一致'))
        } else {
          callback()
        }
      }
    }
  }
</script>

<style lang="less">
  .el-icon-plus {
    border: 1px dashed #d9d9d9;
  }

  .upload {
    .el-upload {
      margin-top: 30px;
      border: 1px dashed #d9d9d9;
    }
  }

  .editHeadImg {
    .el-divider--horizontal {
      margin: 10px 0;
      margin-left: 8px;
    }
    .el-divider__text.is-left {
      left: 0;
    }
  }
</style>

<style lang="less" scoped>
  .username {
    margin-top: 107px;
  }

  .usertime {
    margin-top: 190px;
    display: flex;
    flex: 1;
    text-align: right;
  }

  .row-small {
    margin-left: 0px;
  }

  .userinfo {
    background-color: #bac9e2;
    color: #58a3f7;
    font-size: 18px;
    margin-left: 0px;
  }

  .userrole {
    margin-top: 12px;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .usetip {
    color: #409eff;
    margin-left: 55px;
  }

  .edit-type {
    padding-left: 20px;
    .img {
      float: left;
      width: 60px;
      text-align: center;
      img {
        transform: scale(0.7);
      }
    }
    .text {
      line-height: 30px;
      margin-left: 10px;
      display: inline-block;
    }
  }

  .imgCode {
    vertical-align: middle;
  }
</style>
